import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_trade/pages/trade_receive.dart';
import 'package:aichat_flutter_wallet/module/module_trade/pages/trade_transfer.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/utils/utils.dart';

import '../../../module_common/provider/user_settings_provider.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/widgets/dialog/kai_bottom_tip_dialog.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../../../module_common/widgets/token_widget/token_logo.dart';
import '../../module_create_wallet/pages/set_pass_page.dart';
import '../widgets/trade_list.dart';

class TradeTransactionsPage extends StatefulWidget {
  final String? contract;
  final String contractType;
  Token? token;
  TradeTransactionsPage({super.key, this.contract, this.token, required this.contractType});

  @override
  _TradeTransactionsPage createState() => _TradeTransactionsPage();
}

class _TradeTransactionsPage extends State<TradeTransactionsPage> {
  late TokenInfoNotifier tokenInfoNotifier;

  @override
  void initState() {
    super.initState();
    getData(widget.token!);
  }

  @override
  void dispose() {
    tokenInfoNotifier.destroy();
    super.dispose();
  }

  backWallet() {
    Navigator.of(context).pop();
  }

  getData(Token token) {
    try {
      setState(() {
        widget.token = token;
      });

      tokenInfoNotifier = context.read<TokenInfoNotifier>();
      tokenInfoNotifier.setToken(token, context.read<TokenListNotifier>());
      context.read<TokenListNotifier>().updateTokenBalance(token).then((val) {
        context.read<TokenInfoNotifier>().updateToken(val);
      });
    } catch (e) {
      kaiPrint(e);
    }
  }

  Widget sheetList(Token _token) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        GestureDetector(
          onTap: () {
            // 转账
            bool isSetPass = context.read<UserSettingsProvider>().hasPassword();
            if (!isSetPass) {
              Utils.showBottomSheetDialog(
                  context,
                  KaiBottomTipDialog(
                    type: DialogType.PASSWORD,
                    Confirm: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => SetPassPage(
                                  type: '4',
                                )),
                      );
                    },
                  ));
              return;
            }
            Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return TradeTransferPage(contract: _token.contract, twoBack: true);
            })).then((val) {
              if (val != null) {
                getData(val);
              }
            });
          },
          child: Column(
            children: [
              Container(
                width: 46.w,
                height: 46.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: AppColors.c_F6F3FF,
                  borderRadius: BorderRadius.circular(23.w),
                ),
                child: Image.asset(
                  'assets/images/wallet-trade/send.png',
                  width: 22.w,
                  height: 22.w,
                ),
              ),
              SizedBox(
                height: 7.w,
              ),
              Text('Transfer',
                  style: TextStyle(color: AppColors.c_333333, fontSize: 12.sp, fontWeight: FontWeight.w400))
            ],
          ),
        ),
        SizedBox(
          width: 100.w,
        ),
        GestureDetector(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return TradeReceivePage(
                contract: _token.contract,
                contractType: _token.contractType,
              );
            }));
          },
          child: Column(
            children: [
              Container(
                width: 46.w,
                height: 46.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: AppColors.c_F6F3FF,
                  borderRadius: BorderRadius.circular(23.w),
                ),
                child: Image.asset(
                  'assets/images/wallet-trade/receive.png',
                  width: 22.w,
                  height: 22.w,
                ),
              ),
              SizedBox(
                height: 7.w,
              ),
              Text('Receive', style: TextStyle(color: AppColors.c_333333, fontSize: 12.sp, fontWeight: FontWeight.w400))
            ],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    Token? _token = widget.token;

    return WillPopScope(
      onWillPop: () async {
        // 捕获物理返回按钮的操作
        // 返回false表示阻止默认的返回操作
        // 返回true表示允许默认的返回操作
        // 在这里你可以执行自定义的逻辑

        // 跳转到指定页面0
        backWallet();
        return false;
      },
      child: Scaffold(
        body: Consumer<TokenInfoNotifier>(builder: (c, model, topWidget) {
          Token? _token = model.token;
          return Container(
              color: AppColors.c_white,
              child: Column(
                children: [
                  PageHeaderCom(
                    title: _token.symbol,
                    definedGoBack: true,
                    goBack: backWallet,
                    showBottomBorder: false,
                  ),
                  SizedBox(
                    height: 10.w,
                  ),
                  Stack(
                    clipBehavior: Clip.none,
                    children: [
                      TokenLogo(
                        token: _token,
                        size: 40.w,
                      ),
                      Visibility(
                          visible: _token.contractType != TokenType.native.name,
                          child: Positioned(
                            right: -3.w,
                            bottom: -1.w,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(16.w),
                              child: PublicImage(
                                  width: 16.w,
                                  height: 16.w,
                                  image: context.read<WalletInfoNotifier>().walletChain!.logo),
                            ),
                          ))
                    ],
                  ),
                  SizedBox(
                    height: 10.w,
                  ),
                  Text(
                    null == _token.balance
                        ? '0.00'
                        : Utils.formatStringBalance(_token.balance ?? '0',
                            fractionDigits: Config.balanceFixedNum, trimDecimalZero: true),
                    style: TextStyle(
                        fontSize: 22.sp,
                        fontWeight: FontWeight.bold,
                        fontFamily: '_Din',
                        color: AppColors.c_333333,
                        height: 26.w / 22.w),
                  ),
                  Text(
                    '≈\$${null == _token.valueusd ? '0.00' : Utils.formatStringBalance(_token.valueusd!, fractionDigits: 2, trimDecimalZero: false)}',
                    style: TextStyle(
                        fontSize: 12.sp, fontWeight: FontWeight.w400, color: AppColors.c_BEBDCA, height: 17.w / 12.w),
                  ),
                  SizedBox(
                    height: 10.w,
                  ),
                  Visibility(
                      visible: widget.contractType == TokenType.token20.name &&
                          widget.contract != null &&
                          widget.contract!.length > 0,
                      child: IntrinsicWidth(
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 7.w),
                          decoration: BoxDecoration(
                            color: AppColors.c_F6F6F6,
                            borderRadius: BorderRadius.circular(50.w),
                          ),
                          child: GestureDetector(
                            onTap: () {
                              bool isCopySuccess = Utils.copyText(_token.contract);
                              Toast.show(context,
                                  position: Dpositon.bottom,
                                  message: isCopySuccess ? 'Copied successfully' : 'Copy failed',
                                  status: isCopySuccess ? '1' : '2');
                            },
                            child: Row(
                              children: [
                                Text(
                                  Utils.formatAddress(
                                    _token.contract,
                                  ),
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    fontWeight: FontWeight.w400,
                                    color: AppColors.c_868391,
                                  ),
                                ),
                                SizedBox(
                                  width: 5.w,
                                ),
                                Image.asset(
                                  'assets/images/common/copy.png',
                                  width: 16.w,
                                  height: 16.w,
                                )
                              ],
                            ),
                          ),
                        ),
                      )),
                  SizedBox(
                    height: 20.w,
                  ),
                  sheetList(_token),
                  SizedBox(
                    height: 20.w,
                  ),
                  Container(
                    height: 6.w,
                    color: AppColors.c_F6F6F6,
                  ),
                  SizedBox(
                    height: 10.w,
                  ),
                  Expanded(child: TradeList()),
                  SizedBox(
                    height: 10.w + MediaQuery.of(context).padding.bottom,
                  ),
                ],
              ));
        }),
      ),
    );
  }
}
